package cc.lishixi.book.controller;

import cc.lishixi.book.entity.Book;
import cc.lishixi.book.entity.LendInfo;
import cc.lishixi.book.service.BookInfoService;
import cc.lishixi.book.service.BookService;

import cc.lishixi.book.service.LendInfoService;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by LiShixi on 2016/7/23 0023.
 * http://www.lishixi.cc
 */
@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    LendInfoService lendInfoService;
    @Autowired
    BookInfoService bookInfoService;

    List<Book> books;

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    @RequestMapping("list")
    public String list(Model model) {
        model.addAttribute("books", bookService.list());
        return "book/list";
    }

    @RequestMapping("add")
    public String add(@RequestParam Book book, Model model) {
        boolean r = bookService.add(book);
        model.addAttribute("result", r);
        return "book/add";
    }

    @RequestMapping("find")
    @ResponseBody
    public String find(@RequestParam Integer selType,@RequestParam(required = false) String val){
        List<Book> books;
        switch (selType){
            case 0:books=bookService.findByName(val);
            break;
            case 1:books=bookService.findByIsbn(val);
                break;
            case 2:books=bookService.findBypublisher(val);
                break;
            case 3:books=bookService.findByAuthor(val);
                break;
            default:
                return "非法参数："+selType;

        }
        if(!books.isEmpty()){
            StringBuilder ss=new StringBuilder();
            for(int i=0;i<books.size();i++){
                Book b=books.get(i);
                ss.append(String.format("%s-%s-%s\n",b.getName(),b.getAuthors(),b.getPublisher()));
            }
            return ss.toString();
        }
        return "未找到";
    }
    @RequestMapping("borrow")
    @ResponseBody
    public String borrow(@RequestParam(required = false) String cardId,
                         @RequestParam (required = false)String idsn){
        boolean borrow = bookInfoService.isBorrow(idsn);
        if(borrow){

        }
        /*论文提交的日期提前了，不得不不省了*/
        /*判断书能不能借？借书人的最大借书数*/
        /*这里就直接过吧*/
        LendInfo l = new LendInfo();
        l.setReaderId(cardId);
        l.setBookcode(idsn);
        boolean add = lendInfoService.add(l);
        System.out.println("add = " + add);
        return "添加成功";
    }
}
